#!/bin/bash

# 进入当前脚本所在目录
PWD=$(cd "$(dirname "$0")" && pwd)
cd "$PWD"

# 日志文件路径
DCS_LOG="$PWD/operation.log"

# 环境变量文件
ENV_FILE="$PWD/ops.env"

# 检查 docker-compose 是否可用
if ! command -v docker-compose &> /dev/null; then
  echo "Error: docker-compose is not installed."
  exit 1
fi

# 加载环境变量
if [ -f "$ENV_FILE" ]; then
  source "$ENV_FILE"
else
  echo "Error: $ENV_FILE not found."
  exit 1
fi

# 创建日志文件（如果不存在）
[ ! -f "$DCS_LOG" ] && touch "$DCS_LOG"

# 展示部署信息
function showinfo() {
    echo "========== 🚀 RPA Deployment Info =========="
    echo "📦 Name       : $NAME"
    echo "🔖 Version    : $VERSION"
    echo "🗄️  MySQL      : ${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DATABASE}"
    echo "🛢️  Redis      : ${REDIS_HOST}:${REDIS_PORT}"
    echo "🌐 Flower     : http://${WEB_HOST}:5555"
    echo "🌐 Web Access : http://${WEB_HOST}:${WEB_PORT}"
    echo "============================================"
}


# 写入操作日志
function operation_log() {
    echo "[`date +"%F %T"`] `basename $0` $COM N=$NAME PORT=${WEB_PORT} V=$VERSION DB_HOST=${MYSQL_HOST} DB_PORT=${MYSQL_PORT} DB_DATABASE=${MYSQL_DATABASE}" >> "$DCS_LOG"
}

# 执行命令
COMMAND=$1

case "$COMMAND" in
  "start")
    docker-compose up -d
    showinfo
    operation_log
    ;;
  "stop")
    docker-compose stop
    operation_log
    ;;
  "restart")
    docker-compose restart
    operation_log
    ;;
  "ps")
    docker-compose ps
    ;;
  "down")
    docker-compose down
    operation_log
    ;;
  "downv")
    docker-compose down -v
    operation_log
    ;;
  "config")
    docker-compose config
    ;;
  "showinfo")
    showinfo
    ;;
  *)
    echo "Usage: bash $0 [start|stop|down|downv|ps|restart|showinfo|config]"
    ;;
esac
